package com.example.demo.controller;

import com.example.demo.model.User;
import com.example.demo.model.UserDTO;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by song on 2017/1110.
 */
@RestController
@RequestMapping("/api/v1")
public class UserController{
    @PostMapping("/user/login")
    public Response login(@RequestBody UserDTO userDTO, HttpServletRequest request, HttpServletResponse response) {
        if (userDTO.getPassword().equals("admin") && userDTO.getUsername().equals("admin")) {
            Cookie cookie = new Cookie("token", "token");
            cookie.setMaxAge(900000);
            cookie.setPath("/");
            response.addCookie(cookie);
            return new Response("200", "");
        }else
            return new Response("500", "登录失败!");
    }

    @GetMapping("/user/logout")
    public Response logout(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (null==cookies) {
            System.out.println("没有cookie");
        } else {
            for(Cookie cookie : cookies){
                //如果找到同名cookie，就将value设置为null，将存活时间设置为0，再替换掉原cookie，这样就相当于删除了。
                if(cookie.getName().equals("token")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return new Response("200", "已退出");
    }


    @GetMapping("/user")
    public Object check(@CookieValue(value = "token",
            defaultValue = "") String cookieValue) {
        if(cookieValue.equals(""))
            return new Response("200", "");
        else
            return new CookieDTO(true, new User());
    }


    @Data
    @AllArgsConstructor
    class Response{
        String status;
        String msg;
    }

    @Data
    @AllArgsConstructor
    class CookieDTO{
        boolean success;
        User user;
    }

}
